package com.tater.loadbalance.impl;

import cn.hutool.core.util.StrUtil;
import com.tater.config.NettyConfig;
import com.tater.loadbalance.ILoadBalance;
import com.tater.loadbalance.Service;
import com.tater.pojo.ResponseTime;
import com.tater.zkwatcher.ZKWatcher;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 最小响应时间负载均衡器
 */
@Component
public class ResponseLoadBalance implements ILoadBalance {


    @Autowired
    ZKWatcher zkWatcher;


    @Override
    public Service selectService() {
        List<String> serviceList = zkWatcher.getServiceList();
        if (serviceList.size() > 0) {
            Service service = new Service();

            long time = 100000;
            for (String address : serviceList) {
                //获取节点数据
                String path=NettyConfig.SERVER_NODE + "/" + address;
                ResponseTime responseTime = zkWatcher.getZkClient().readData(path,new Stat());
                if (responseTime==null){
                    continue;
                }
                long o = responseTime.getDoneTime();
                System.out.println(path+" 上次响应时间"+o);
                if (o < time) {
                    time = o;
                    String[] split = StrUtil.split(address, ":");
                    service.setHost(split[0]);
                    service.setPort(Integer.parseInt(split[1]));
                }

            }
            return service;
        }
        return null;
    }

    @Override
    public void setRpcTime(String path, long costTime) {
        //设置本次调用时间
        ResponseTime time=new ResponseTime();
        time.setCallTime(LocalDateTime.now());
        time.setDoneTime(costTime);
        zkWatcher.setData(path, time);
    }


}
